import cv2
import numpy as np
#读取图像
img = cv2.imread('6.jpg')
cv2.imshow('Original Image', img)

points = []
#定义鼠标回调函数
def mouse_click(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        points.append([x, y])
        cv2.circle(img, (x, y), 5, (0, 255, 0), -1)
#绑定鼠标回调函数
cv2.namedWindow('Original Image')
cv2.setMouseCallback('Original Image', mouse_click)
#循环检测按键
while True:
    cv2.imshow('Original Image', img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
#判断边界点数量是否为4
if len(points) != 4:
    print('Please select exactly 4 points.')
    exit()

src_points = np.float32(points)
dst_points = np.float32([[0, 0], [500, 0], [500, 500], [0, 500]])
#进行透视变换
M = cv2.getPerspectiveTransform(src_points, dst_points)
warped_img = cv2.warpPerspective(img, M, (500, 500))

cv2.imshow('Warped Image', warped_img)
cv2.waitKey(0)
# 继续显示原始图像
cv2.imshow('Original Image', img)
cv2.waitKey(0)

cv2.destroyAllWindows()